package com.rky.crowd.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.rky.crowd.constant.AccessPassResources;
import com.rky.crowd.constant.CrowdConstant;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 0x_Jss
 * @date 2022年02月25日 15:13
 * @description
 */
@Component
public class CrowdAccessFilter extends ZuulFilter {
    @Override
    public String filterType() {
        //这里返回"pre"意思是在目标微服务前执行过滤
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        //通过RequestContext对象获取当前请求对象
        HttpServletRequest request = requestContext.getRequest();
        //获取servletPath值
        String servletPath = request.getServletPath();
        //根据servletPath判断当前请求是否对应可以直接放行的特定功能
        boolean containsResult = AccessPassResources.PASS_RES_SET.contains(servletPath);
        if (containsResult){
            //如当前请求是可直接放行的特定功能请求则返回false放行
            return false;
        }
       //判断当前请求是否为静态资源
        return !AccessPassResources.judgeCurrentServletPathWhetherStaticResource(servletPath);
    }

    @Override
    public Object run() throws ZuulException {
        //获取当前请求及对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //获取当前Session对象
        HttpSession session = request.getSession();
        //尝试从Session对象中获取已登录的用户
        Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
        //判断loginMember是否为空
        if (loginMember == null){
            //从requestContext对象中获取Response对象
            HttpServletResponse response = requestContext.getResponse();
            //将提示消息存入Session域
            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_ACCESS_FORBIDEN);
            //重定向到auth-consumer工程中的登录页面
            try {
                response.sendRedirect("/auth/member/to/login/page");
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return null;
    }
}